package com.ecp.commons.msg;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import javax.annotation.PostConstruct;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.ecp.commons.task.Task;

@Repository("clusterMSGServer")
public class ClusterMSGServer {

	private static String	broadcastAddress	= "255.255.255.255";
	private static int		targetPort			= 3001;

	protected static Logger	log					= Logger.getLogger(ClusterMSGServer.class);

	@Autowired
	private Task			cacheMSGTask;

	public static void sendData(String msg) {
		log.debug("broadcast: " + msg);
		DatagramSocket ds = null;
		try {
			ds = new DatagramSocket();
			DatagramPacket dp = new DatagramPacket(msg.getBytes(), msg.getBytes().length,
					InetAddress.getByName(broadcastAddress), targetPort);
			ds.send(dp);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (ds != null) {
				ds.close();
			}
		}
	}

	@PostConstruct
	private void receiveData() {

		new Thread() {
			@Override
			public void run() {
				DatagramSocket ds = null;
				try {
					ds = new DatagramSocket(targetPort);
					byte[] buf = new byte[1024];
					DatagramPacket dp = new DatagramPacket(buf, 1024);
					String strRecv;
					String[] msg;
					for (;;) {
						ds.receive(dp);
						strRecv = new String(dp.getData(), 0, dp.getLength());
						msg = strRecv.substring(1, strRecv.length() - 1).replaceAll(",\\s+", ",").split(",");
						if (msg[0].equals("cache")) {
							msg[1] = "receive";
							cacheMSGTask.setParams(msg);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					if (ds != null) {
						ds.close();
					}
				}
			}
		}.start();
		log.info("Start cluster server.[" + broadcastAddress + ":" + targetPort + "]");
	}
}
